package com.etone.ibatistest.dao;

import java.io.IOException;
import java.io.Reader;
import java.sql.SQLException;
import java.text.NumberFormat;
import java.util.List;

import com.etone.ibatistest.entity.User;
import com.etone.ibatistest.entity.UserParameter;
import com.etone.ibatistest.test.H2Test;
import com.ibatis.common.resources.Resources;
import com.ibatis.sqlmap.client.SqlMapClient;
import com.ibatis.sqlmap.client.SqlMapClientBuilder;

public class H2UserDaoImpl{

	private static SqlMapClient sqlMapClient = null;
	
	public static SqlMapClient getSqlMapClient() {
		return sqlMapClient;
	}
	static{
		try {
			Reader reader = Resources.getResourceAsReader("com/etone/ibatistest/H2Map/SqlMapConfig.xml");
			sqlMapClient = SqlMapClientBuilder.buildSqlMapClient(reader);
			reader.close();
		} catch (IOException e) {
		}
	}

	public void createTable(UserParameter para){
		
		try {
			sqlMapClient.update("createTable", para);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
	}
	
	public List<User> selectObject(String tableName){
		List<User> list = null;
		try {
			list = sqlMapClient.queryForList("selectOne",tableName);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return list;
	}
	
	public void insertTable(UserParameter para){
		
		try {
			sqlMapClient.insert("insertTable",para);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	
	public void dropTable(String tableName){
		try {
			sqlMapClient.update("dropTable",tableName);
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
	
	public void insertTable(UserParameter para, List<String> list){
		
		try {
			sqlMapClient.startTransaction();
			sqlMapClient.startBatch();
			long t1 = System.currentTimeMillis();
			for(String str :list){
				para.setTableField(str);
				sqlMapClient.insert("insertTable",para);
			}
			long t2 = System.currentTimeMillis();
			sqlMapClient.executeBatch();
			sqlMapClient.commitTransaction();  
			long t3 = System.currentTimeMillis();
			System.out.println("[" + this.getClass().getName()
			+"] cost time(t1~t2) : " 
			+ NumberFormat.getInstance().format(t2-t1) + "ms"
			+"(t2~t3) : "
			+ NumberFormat.getInstance().format(t3-t2) + "ms");
//			sqlMapClient.endTransaction();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
	}
}
